package gosnoopers.fr;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import common.PickImage;
import components.MultipartUtility;

public class FormSecond extends Activity implements OnClickListener {

	private static final int ACTION_TAKE_PHOTO = 100;
	private static final int REQUEST_CODE = 1;
	public static final String KEY_ID_VICTIM = "victim";
	public static List<Bitmap> imageArr = new ArrayList<Bitmap>();

	private String path;
	private String id;
	private Bitmap bitmap;
	
	private ImageView mImgDone;
	private Button mBtnTakePhoto;
	private Button mBtnChooseLibrary;
	private GridView gridView;
	
	private ProgressBar mProBarUploading;
	private ProgressBar mProBarUploading2;
	private ProgressBar mProBarWaiting;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.fragment_photo_user);
		
		
		TextView text_view_landing_page_header = (TextView) findViewById(R.id.text_view_landing_page_header);
        text_view_landing_page_header.setText("Upload photo");
		init();
		setEventForButton();
	}

	public void init() {

		gridView = (GridView) findViewById(R.id.grid_photo_user);
		
		mImgDone = (ImageView) findViewById(R.id.image_done);
		mBtnChooseLibrary = (Button) findViewById(R.id.btn_choose_library);
		mBtnTakePhoto = (Button) findViewById(R.id.btn_take_photo);
		id = getIntent().getStringExtra(KEY_ID_VICTIM);
		mProBarUploading = (ProgressBar) findViewById(R.id.probar_uploading);
		mProBarUploading2 = (ProgressBar) findViewById(R.id.probar_uploading2);
		mProBarWaiting = (ProgressBar) findViewById(R.id.probar_waiting);
		mImgDone.setVisibility(View.VISIBLE);		
		mProBarWaiting.setVisibility(View.GONE);
       
        gridView.setAdapter(new ImageAdapter(this));
        
	}
	//*********************key down********************
	final Context context = this;
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	        // your code
	    	
	    	
	    		
	    		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);
				alertDialogBuilder.setTitle("GOSNOOPERS");
				alertDialogBuilder
				.setMessage("Are you sure go back?")
				.setCancelable(false)
				.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						if(FormFirst.isUpdate)
							finish();
						else{
							Intent form1 = new Intent(getApplicationContext(), FormFirst.class);
							startActivity(form1);
						}
					}
				  })
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
	    	
	        return true;
	    }

	    return super.onKeyDown(keyCode, event);
	}
	public void setEventForButton() {
		mBtnTakePhoto.setOnClickListener(this);
		mBtnChooseLibrary.setOnClickListener(this);
		mImgDone.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_choose_library:
			PickImage.pickImage(FormSecond.this);
			break;
		case R.id.btn_take_photo:
			dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
			break;
		case R.id.image_done:
			//mImgDone.setEnabled(false);
			mImgDone.setVisibility(View.GONE);
			mProBarWaiting.setVisibility(View.VISIBLE);
			Intent goToNextActivity = new Intent(getApplicationContext(), GmapActivity.class);
			goToNextActivity.putExtra(GmapActivity.KEY_ID_VICTIM, id);
            startActivity(goToNextActivity);
			/*if (ConnectionDetectorUtil.isConnectingToInternet(FormSecond.this)) {
				new PostPhotoToServer(id, imageArr).execute();
			}*/
			break;
		default:
			break;
		}
	}

	/**
	 * on call to camera
	 */
	private void dispatchTakePictureIntent(int actionCode) {
		Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
        startActivityForResult(cameraIntent, actionCode); 
	}
	
	/**
	 * onActivityResult. Receiver image from you choosed
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case ACTION_TAKE_PHOTO:
			if(resultCode  == RESULT_OK && requestCode == ACTION_TAKE_PHOTO) {
				if(data != null) {
					bitmap = null;
					bitmap = (Bitmap) data.getExtras().get("data"); 
					new PostPhotoToServer(id, bitmap,0).execute();
				}
			}
			break;
		case PickImage.REQUEST_CODE_PICK_IMAGE:
			if((resultCode == RESULT_OK) && (data != null)) {
				bitmap = null;
				bitmap = PickImage.getPath(data.getData(), FormSecond.this);
				new PostPhotoToServer(id, bitmap,1).execute();
			}
			break;
		default:
			break;
		}
	}
	
	
	public static String messagePostPhoto = "";
	
	/**
	 * Class asynctask post photo to server
	 */
	private class PostPhotoToServer extends AsyncTask<Void, Void, Boolean> {
		
		private Bitmap mBitmap;
		private String id;
		private int key;
		
		
		public PostPhotoToServer(String id, Bitmap bitmap,int _key) {
			this.id = id;
			this.mBitmap = bitmap;
			this.key = _key;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if(key==0)
				mProBarUploading.setVisibility(View.VISIBLE);
			else
				mProBarUploading2.setVisibility(View.VISIBLE);
		}
		@Override
		protected Boolean doInBackground(Void... params) {
			
			return execuseUploadPhoto(id,mBitmap);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			// error is false -> result is true
			if(result == false) {
				Toast.makeText(getApplicationContext(), "Upload complete", Toast.LENGTH_SHORT).show();
				imageArr.add(mBitmap);
				gridView.setAdapter(new ImageAdapter(context));
				mProBarUploading.setVisibility(View.GONE);
				mProBarUploading2.setVisibility(View.GONE);
				
			}else{
				mProBarUploading.setVisibility(View.GONE);
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);
				alertDialogBuilder.setTitle("GOSNOOPERS");
				alertDialogBuilder
				.setMessage(messagePostPhoto)
				.setCancelable(false)
				.setNegativeButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
			}
		}
		
		
		/**
		 * @author TienLQ
		 *  Method upload photo
		 */
		private boolean execuseUploadPhoto (String id, Bitmap bm){
			String uRLPost = "http://gosnoopers.com/victimes/app/uploadImages?uuid="+id;
			try{
					File file = getFilePath(bm);
					
					MultipartUtility multipart = new MultipartUtility(uRLPost,"UTF-8");
					
		            multipart.addFormField("id", id);
		            multipart.addFilePart("image", file);
		            
		           List<String> response = multipart.finish();
		            
		           System.out.println("SERVER REPLIED:");
		             
		            for (String line : response) {
		                System.out.println(line);
		                JSONObject jsonDataResult= new JSONObject(line);
		                Log.d("POST PHOTO ", "DEBUG: "+jsonDataResult);
		                messagePostPhoto = jsonDataResult.getString("message");
		                return jsonDataResult.getBoolean("error");
		            }
			} catch(Exception e) {
				e.printStackTrace();
			}
			return false;
		}
		
		/**
		 * @author TienLQ
		 * Convert from bitmap to File for upload
		 * 
		 */
		private File getFilePath(Bitmap bm) {
			String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
			
			Log.i("ImageUtil", "extStorageDirectory: " + extStorageDirectory);
			OutputStream outStream = null;
			File file = new File(extStorageDirectory, "c12xcxcxccvcx" + "." + "JPEG");
			try {
				outStream = new FileOutputStream(file);
				bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
				try {
					outStream.flush();
					outStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return file;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
	//******************set bitmap to image adapter ****************
	public class ImageAdapter extends BaseAdapter 
    {
        private Context context;
 
        public ImageAdapter(Context c) 
        {
            context = c;
        }
 
        //---returns the number of images---
        public int getCount() {
            return imageArr.size();
        }
 
        //---returns the ID of an item--- 
        public Object getItem(int position) {
            return position;
        }
 
        public long getItemId(int position) {
            return position;
        }

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			 ImageView imageView;
            if (arg1 == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(5, 5, 5, 5);
            } else {
                imageView = (ImageView) arg1;
            }
            imageView.setImageBitmap(imageArr.get(arg0));
            return imageView;
			
		}
    }    
	
}